package com.lrm.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 阿里云 OSS 工具类
 */

@Component//交给容器管理，就不用新建对象，直接注入就可以
public class AliOSSUtils {
/*    @Autowired
    private AliOSSProperties aliOSSProperties;*/

    /**
     * 实现上传图片到OSS
     */
    public String upload(MultipartFile file) throws IOException {
        System.out.println("----------进入了upload------------");
        //将参数交给properties集中配置管理，并用Value注解注入外部属性配置
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
//    @Value("${aliyun.oss.accessKeyId}")
        String accessKeyId = "LTAI5tAYAEz5YsKN5MWHXpAy";
//    @Value("${aliyun.oss.accessKeySecret}")
        String accessKeySecret = "frepCi53J3TJTB2mAVVQmRF2mxQJSM";
//    @Value("${aliyun.oss.bucketName}")
        String bucketName = "web-tlias-planker";

        // 获取上传的文件的输入流
        InputStream inputStream = file.getInputStream();
        System.out.println("----------获取文件上传流------------");

        // 避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
        System.out.println("----------避免文件覆盖------------");

        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);
        System.out.println("----------上传文件到OSS------------");

        //文件访问路径
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
        // 关闭ossClient
        ossClient.shutdown();
        return url;// 把上传到oss的路径返回
    }

}
